home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / MYIO.ZIP / MYLINE.CPP < prev    next >
C/C++ Source or Header  |  1995-11-02  |  2KB  |  77 lines

  1. // myLine.cpp
  2. //
  3. // 13 Jun 93   Init array[0] = NUL in case it is reference before use
  4. //             memcpy() adjusted to also copy terminating NUL from is.get()
  5. //             when extending buffer
  6. //
  7.  
  8. # include <iostream.h>
  9. # include "myLine.h"
  10. # if defined(_MSC_VER)
  11. #  include <memory.h>
  12. # else
  13. #  include <stdlib.h>
  14. # endif
  15.  
  16.     // Class implementation
  17.  
  18. myLine::myLine (short buflen)
  19.     : len(buflen), mybuf(new char[len]), xalloc(1)
  20. {
  21.     mybuf[0] = 0;
  22. }
  23.  
  24. myLine::myLine (char * usebuf, short buflen)
  25.     : len(buflen), mybuf(usebuf), xalloc(0)
  26. {
  27.     mybuf[0] = 0;
  28. }
  29.  
  30. myLine::~myLine (void)
  31. {
  32.     if (xalloc)
  33.         delete [] mybuf;
  34. }
  35.  
  36.  
  37. istream &
  38. operator>> (istream & is, myLine & l)
  39. {
  40. # if AUTO_GROW
  41.     if (!l.xalloc)              // It's not my buf, so it can't be grown
  42.     {
  43. # endif
  44.         is.get (l.mybuf, l.len);
  45.         if (is.peek() == '\n')
  46.             is.get();           // Remove newline from stream
  47. # if AUTO_GROW
  48.     }
  49.     else
  50.     {
  51.         int idx = 0;
  52.         l.mybuf[0] = 0;     // Terminate in case is.good() isn't
  53.         for (int eol = 0; !eol && is.good(); )
  54.         {
  55.             int toget = l.len - idx;
  56.             is.get (l.mybuf + idx, toget);
  57.             int chrs = is.gcount();
  58.             if (is.peek() == '\n')
  59.             {
  60.                 ++eol;       // Must be eol or eof
  61.                 is.get();    // Clear newline
  62.             }
  63.             else if (chrs)
  64.             {                // Extend buffer
  65.                 idx += chrs; // Add to index
  66.                 l.len = short(l.len + ALLOC_LEN);
  67.                 char * tmp = new char[l.len];
  68.                 memcpy (tmp, l.mybuf, idx + 1);
  69.                 delete [] l.mybuf;
  70.                 l.mybuf = tmp;
  71.             }
  72.         }
  73.     }
  74. # endif
  75.     return is;
  76. }
  77.